package com.yuanfengPlus.incomeitem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yuanfengPlus.basicInfoManage.logisticscompany.model.LogisticsCompanyInfo;
import com.yuanfengPlus.incomeitem.dao.IIncomeItemMapper;
import com.yuanfengPlus.incomeitem.model.IncomeItemInfo;
import com.yuanfengPlus.incomeitem.service.IIncomeItemService;
import com.yuanfengPlus.utils.PageResult;
import com.yuanfengPlus.utils.Result;
import com.yuanfengPlus.utils.SnowflakeIdWorker;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class IncomeItemServiceImpl implements IIncomeItemService {
    @Resource
    private IIncomeItemMapper iiim;
    @Override
    public Result<String> insert(IncomeItemInfo incomeItemInfo) {
        if (incomeItemInfo.getIncome_name() == null)
            return Result.failure(500,"支出项目名称不能为空");
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(3);
        incomeItemInfo.setIncome_ID(snowflakeIdWorker.nextId());
        incomeItemInfo.setIncome_operate_time(new java.sql.Timestamp(System.currentTimeMillis()));
        incomeItemInfo.setIncome_review_time(new java.sql.Timestamp(System.currentTimeMillis()));
        Integer insert = iiim.insert(incomeItemInfo);
        return insert > 0 ? Result.success("添加成功") : Result.failure(500,"添加失败");
    }

    @Override
    public Result<String> update(IncomeItemInfo incomeItemInfo) {
        Integer update = iiim.update(incomeItemInfo);
        return update > 0 ? Result.success("修改成功") : Result.failure(500,"修改失败");
    }

    @Override
    public PageResult select(Map<String, Object> params) {
        // 检查并设置默认值
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 10);

        // 确保 pageNum 和 pageSize 不为 null
        if (pageNum == null || pageSize == null) {
            throw new IllegalArgumentException("pageNum 和 pageSize 不能为 null");
        }

        PageHelper.startPage(pageNum, pageSize);

        // 确保 ilocm 不为 null
        if (iiim == null) {
            throw new IllegalStateException("ilocm 未正确初始化");
        }

        Page<IncomeItemInfo> page = iiim.select(params);

        // 确保 page 不为 null
        if (page == null) {
            throw new IllegalStateException("查询结果为空");
        }

        return new PageResult(page.getTotal(), page.getResult());
    }
}
